define(['moment'], function (moment) {
    return ['$scope','$rootScope', '$filter', '$stateParams', '$mdDialog', 'config', 'MMWService', '$css', '$timeout',
        function ($scope, $rootScope,$filter, $stateParams, $mdDialog, config, $MMWService, $css, $timeout) {
            $scope.init = function () {
                $css.add('JSplugins/angular-gantt/angular-gantt.min.css');
                $css.add('JSplugins/angular-ui-tree/angular-ui-tree.min.css');
                $css.add('JSplugins/angular-gantt/angular-gantt-plugins.min.css');
                $css.add('JSplugins/angular-gantt/angular-gantt-progress-plugin.min.css');
                //$css.add('JSplugins/angular-gantt/angular-gantt-tooltips-plugin.min.css');
                $scope.searchConditionList = [];
                //$scope.queryMode = 'list';
                $scope.queryMode = 'list';
                $scope.options = {
                    orderBy:'model.seq',
                    maxHeight:0,
                    columnWidth:28
                };
                $scope.codeList = [
                    //派工日期
                    {name:$filter('translate')('A03.query.fields.WorkDate'), column_name:'WorkDate',
                        value_s:new Date(), value_e:new Date(), data_type:'SE', require:true},
                    {name:$filter('translate')('A03.query.fields.areaNo'), column_name:'AreaNo'},
                    {name:$filter('translate')('A03.query.fields.MoNo'), column_name:'E.MoNo'},
                    {name:$filter('translate')('A03.query.fields.LotNo'), column_name:'A.LotNo'},
                    {name:$filter('translate')('A03.query.fields.opNo'), column_name:'A.OpNo'},
                    //設備編號
                    {name:$filter('translate')('A03.query.fields.EquipmentNo'), column_name:'A.EquipmentNo'},
                    //設備名稱
                    {name:$filter('translate')('A03.query.fields.EquipmentName'), column_name:'B.EquipmentName'},
                    //20231213 add by Ruke for M#133354: [sMES]H5-派工看板增加品號、品名的條件與欄位[昆桐]
                    //產品編號
                    { name: $filter('translate')('A03.query.fields.item_no'), column_name: 'F.ProductNo' },
                    //產品名稱
                    { name: $filter('translate')('A03.query.fields.item_name'), column_name: 'F.ProductName' },
                    //產品規格
                    { name: $filter('translate')('A03.query.fields.ITEMSPEC'), column_name: 'F.ITEMSPEC' },
                    //產品類別
                    { name: $filter('translate')('A03.query.fields.PRODUCTTYPE'), column_name: 'F.PRODUCTTYPE' },
                ];

                $scope.nowDateTime = moment().format('YYYY/MM/DD');
                $scope.dateTimeArray = [];//日期陣列
                $scope.masterList = {};//主查詢
                $scope.detailList = [];//子查詢

                $scope.tableColumnFormatters = {
                    'model.to': function(value, column, row) {
                        if (value && value.format) {
                            return value.format('YYYY/MM/DD');
                        }
                        return value;
                    },
                    'model.from': function(value, column, row) {
                        if (value && value.format) {
                            return value.format('YYYY/MM/DD');
                        }
                        return value;
                    }
                };
                $scope.filterHeader = '<i class="gantt-tree-handle glyphicon" style="top:4px;" ng-class="scope.collapseClass();" ng-click="scope.collapseTrigger();"></i>{{getHeader()}}';
                $scope.PageConfig = {page : 0, page_count : 100};
            };

            $scope.back = function () {
                window.removeEventListener('resize', updateGanntHeight);
                if ($scope.queryMode=='list-detail'){
                    $scope.queryMode='list';
                    $scope.detailList = [];
                } else {
                    $scope.$root.hideMenu();
                    $scope.$root.changeProgram('home', true);
                }

            };
            var _report_data = [];
            $scope.search = function (condition) {
                $MMWService.sendToServer({
                    uri : 'ServicesSTD.Module_SYS.user_custom_report_data_get',
                    content : {
                        report_id:'A03',
                        query_condition_info:condition
                    },
                    success : function(data){
                        _report_data = data.report_data;
                        if(data.report_data.length>0){
                            if($scope.queryMode == 'list-gantt'){
                                $scope.PageConfig.page = 0;
                                $scope.genGantt();
                            } else {
                                $scope.genTable();
                            }
                        }
                        else{
                            $scope.masterList = {};
                            $rootScope.showAlert($filter('translate')('common.msg.no_data'));
                        }
                    }
                });
            };

            $scope.showWorkDate = function(){
                var select_list = [];
                if($scope.dateTimeArray.length>0){
                    $scope.dateTimeArray.forEach(function(dateTime){
                        select_list.push({dateTime:dateTime});
                    });
                    $scope.$root.showSelect({
                        label : 'dateTime',
                        code : 'dateTime',
                        selectCode : $scope.nowDateTime,
                        list : select_list,
                        confirm : function(item, dialog){
                            $scope.nowDateTime = item.dateTime;
                            dialog.hide();
                        }
                    });
                }
            }

            $scope.prevDate = function () {
                var index = $scope.dateTimeArray.indexOf($scope.nowDateTime);
                if(index > 0){
                    $scope.nowDateTime = $scope.dateTimeArray[index-1];
                }
            };

            $scope.nextDate = function () {
                var index = $scope.dateTimeArray.indexOf($scope.nowDateTime);
                if(index < $scope.dateTimeArray.length-1){
                    $scope.nowDateTime = $scope.dateTimeArray[index+1];
                }
            };

            $scope.openDetail = function(item){
                $scope.selectPlotNo = item.plot_no;
                var content = {
                    report_mode: 101,
                    query_condition_info : [
                        {column_name:'LotNo', query_mode:0, value:item.plot_no, merge_condition_model:'AND'},
                        {column_name:'Workdate', query_mode:0, value:item.work_date, merge_condition_model:'AND'},
                        {column_name:'OPNo', query_mode:0, value:item.op_no, merge_condition_model:'AND'},
                        {column_name:'EquipmentNo', query_mode:0, value:item.machine_no, merge_condition_model:'AND'}
                    ]
                };

                $MMWService.reportInfoGet(content, function(itemList){
                   if(itemList.length>0){
                       $scope.queryMode = 'list-detail';
                       $scope.detailList = itemList;
                   }
                   else{
                       $rootScope.showAlert($filter('translate')('common.msg.no_data'));
                   }

                });
            };

            $scope.closeDetail = function(){
                $scope.queryMode = 'list';
                $scope.detailList = [];
            };

            function ParseTemp(dataList, parent, _temp){
                $rootScope.getValueforObj(_temp).forEach(function(item){
                    //console.log(item.name);
                    var data_item = {
                        name:_uuid(),
                        content:item.name,
                        seq:item.seq,
                        from:item.from,
                        to:item.to,
                        item_no:item.item_no, // 20231214 add by Alan for#133354 : 产品编号
                        item_name:item.item_name, // 20231214 add by Alan for#133354 : 产品名称
                        qty:item.qty
                    }
                    dataList.push(data_item);
                    if(parent){
                        parent.children.push(data_item.name);
                    }
                    if(item._temp && $rootScope.getValueforObj(item._temp).length>0){
                        data_item.children = [];
                        ParseTemp(dataList, data_item, item._temp);
                    }
                    //else {
                        data_item.tasks = [{
                            name: '',
                            color:item.color,
                            from:data_item.from,
                            to:data_item.to,
                            progress: {
                                percent: 0,
                                color: '#F1C232'
                            }
                        }];
                    //}
                });
            }
            $scope.genTable = function(){
                $scope.queryMode = 'list';
                $scope.masterList = {};
                $scope.dateTimeArray = [];
                _report_data.forEach(function(item){
                    if(!$scope.masterList[item.work_date]){
                        $scope.dateTimeArray.push(item.work_date);
                        $scope.masterList[item.work_date] = [];
                    }
                    $scope.masterList[item.work_date].push(item);
                });
                $scope.nowDateTime = $scope.dateTimeArray[0];
            }

            // 20231214 add by Alan for#133354 : 产品编号、产品名称
            $scope.ganttSettings = {
                headers:'day',
                datetype:'work_date',
                datetypes:[
                    {column:'work_date', name:$filter('translate')('A03.query.fields.WorkDate'), from:'work_date', to:'work_date'},
                    {column:'plan_date', name:$filter('translate')('A03.query.fields.PlanDate'), from:'plot_start_time', to:'plot_end_time'}
                ],
                ganttGroups: [
                    {column:'mo_no', name:$filter('translate')('A03.query.fields.MoNo'), color:'#559b68', isSelect:true, item_no: 'item_no', item_name: 'item_name', qty:'mo_qty', qty_type:'max'},
                    {column:'plot_no', name:$filter('translate')('A03.query.fields.LotNo'), color:'#b08b62', isSelect:true, item_no: 'item_no', item_name: 'item_name', qty:'plot_qty', qty_type:'max'},
                    {column:'op_no', name:$filter('translate')('A03.query.fields.opNo'), color:'#8975a9', isSelect:true, item_no: 'item_no', item_name: 'item_name', qty:'qty', qty_type:'add'},
                    {column:'machine_no', name:$filter('translate')('A03.query.fields.EquipmentNo'), color:'#4374ba', isSelect:true, item_no: 'item_no', item_name: 'item_name', qty:'qty', qty_type:'add'}
                ]
            }
            // 20220802 modify by Alan for#114744 : 新增甘特圖分頁功能
            // 存放處理過後的甘特圖資料
            var gantt_data = [];
            
            $scope.genGantt = function(){
                var _headers = ['year', 'month', 'week', 'day'];
                $scope.queryMode = 'list-gantt';
                $scope.collapseStatus = false;
                if(_report_data.length>0){
                    $scope.$root.showLoading();
                    var _datetype = $filter('filter')($scope.ganttSettings.datetypes, {column:$scope.ganttSettings.datetype})[0],
                        _temp = {},
                        _groups = $filter('filter')($scope.ganttSettings.ganttGroups, {isSelect:true});

                    //產生標頭
                    $scope.options.viewScale = $scope.ganttSettings.headers;
                    if($scope.options.viewScale == 'day'){
                        $scope.options.headers = ['month', 'day'];
                        $scope.options.columnWidth = 28;
                    }else if($scope.options.viewScale == 'week'){
                        $scope.options.headers = ['month', 'week'];
                        $scope.options.columnWidth = 28;
                    }else if($scope.options.viewScale == 'month'){
                        $scope.options.headers = ['year', 'month'];
                        $scope.options.columnWidth = 28;
                    }else if($scope.options.viewScale == 'year'){
                        $scope.options.headers = ['year'];
                        $scope.options.columnWidth = 28;
                    }

                    _report_data.forEach(function(item){
                        var _str_var = '';
                        _groups.forEach(function(_group_obj, index){
                            var _real_var;
                            if(index !=0)
                                _str_var += '.';
                            _str_var += '_temp[item[_groups[' + index + '].column]]';

                            eval('_real_var = ' + _str_var+';');
                            if(!_real_var){
                                _real_var = {
                                    name:item[_group_obj.column],
                                    from:moment(item[_datetype.from]).set({'hour': 0, 'minute': 0, 'second':0}),
                                    to:moment(item[_datetype.to]).set({'hour': 23, 'minute': 59, 'second':59}),
                                    color:_group_obj.color,
                                    item_no:item[_group_obj.item_no], // 20231214 add by Alan for#133354 : 产品编号
                                    item_name:item[_group_obj.item_name], // 20231214 add by Alan for#133354 : 产品名称
                                    qty:item[_group_obj.qty],
                                    seq:item['op_seq'],
                                    _temp:{}
                                };
                                eval(_str_var+' = _real_var;');
                            } else {
                                if(_real_var.from.diff(item[_datetype.from])>0){
                                    _real_var.from = moment(item[_datetype.from]).set({'hour': 0, 'minute': 0, 'second':0});
                                }
                                if(_real_var.to.diff(item[_datetype.to])<0){
                                    _real_var.to = moment(item[_datetype.to]).set({'hour': 23, 'minute': 59, 'second':59});
                                }
                                if(_group_obj.qty_type == 'max'){
                                    if(_real_var.qty <= item[_group_obj.qty]){
                                        _real_var.qty = item[_group_obj.qty];
                                    }
                                } else {
                                    _real_var.qty += item[_group_obj.qty];
                                }
                            }
                        });
                    });
                    // 20220802 modify by Alan for#114744 : 新增甘特圖分頁功能
                    // 後端回應資料處理後放進gantt_data
                    gantt_data = [];
                    ParseTemp(gantt_data, undefined, _temp);
                    // 20230221 delete by Alan for#127691 : 修正頁數計算
                    // 計算總頁數
                    $scope.PageConfig.total_page = Math.floor((gantt_data.length) / $scope.PageConfig.page_count) + 1;
                    // 清除畫面暫存
                    $scope.data = [];
                    $scope.refresh = true;
                    // 20230221 delete by Alan for#127691 : 移除自動高度調整
                    $timeout(function(){
                        $scope.data = gantt_data.slice(0, $scope.PageConfig.page_count);
                        $scope.refresh = false;
                        $scope.$root.hideLoading();
                    });
                }
            }

            $scope.registerApi = function(api){
                api.core.on.ready($scope, function(_api){
                    $scope.collapseTrigger = function(){
                        $scope.collapseStatus = !$scope.collapseStatus;
                        if($scope.collapseStatus){
                            //_api.tree.collapseAll();
                            $scope.$broadcast('angular-ui-tree:collapse-all');
                        } else {
                            //_api.tree.expandAll();
                            $scope.$broadcast('angular-ui-tree:expand-all');
                        }
                    }
                    $scope.collapseClass = function(){
                        if($scope.collapseStatus){
                            return 'glyphicon-chevron-right';
                        } else {
                            return 'glyphicon-chevron-down';
                        }
                    }
                    _api.tree.on.collapsed($scope, function(row, collapsed){
                        if(collapsed._collapsed){
                            //關起來
                        } else {
                            //打開
                            $scope.collapseStatus = false;
                        }
                    });
                    _api.data.on.change($scope, (newData, OldData) => {
                        $scope.$root.hideLoading();
                    });
                });
            }
            function _uuid() {
              var d = Date.now();
              if (typeof performance !== 'undefined' && typeof performance.now === 'function'){
                d += performance.now(); //use high-precision timer if available
              }
              return 'xxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                var r = (d + Math.random() * 16) % 16 | 0;
                d = Math.floor(d / 16);
                  return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
              });
            }

            $scope.showGantDetail = function(row){
                var _filter_item = {};
                ganttGroups.forEach(function(group){
                    _filter_item[group.column] = row[group.column];
                });
                var _temp_report_data = $filter('filter')(_report_data, _filter_item);
                $scope.$root.showQueryList({
                    header : [,
                        {label: $filter('translate')('A03.list.column6'), code:'item_no'},
                        {label: $filter('translate')('A03.list.column7'), code:'item_name'},
                        {label: $filter('translate')('A03.list.column1'), code:'op_no'},
                        {label: $filter('translate')('A03.list.column2'), code:'op_name'},
                        {label: $filter('translate')('A03.list.column3'), code:'machine_no'},
                        {label: $filter('translate')('A03.list.column4'), code:'machine_name'},
                        {label: $filter('translate')('A03.list.column5'), code:'plot_no'},
                        {label: $filter('translate')('A03.list.column8'), code:'qty'},
                        {label: $filter('translate')('A03.list.column9'), code:'work_date'},
                        {label: $filter('translate')('A03.list.column10'), code:'plot_start_time'},
                        {label: $filter('translate')('A03.list.column11'), code:'plot_end_time'}
                    ],
                    query: function(conditions, feedback){
                        feedback(_temp_report_data);
                    },
                    confirm : function(selectItem, dialogQuery){

                    }
                });
            }

            $scope.ganttSetting = function(){
                $mdDialog.serviceDialog('GanttSetting', {
                    settings:$scope.ganttSettings,
                    callback:function(settings){
                        $scope.ganttSettings = settings;
                        $scope.genGantt();
                    }
                });
            }

            // 20230221 delete by Alan for#127691 : 修改SrollBar對象
            // 20220802 modify by Alan for#114744 : 新增甘特圖分頁功能
            // 監聽頁面自動更換資料
            $scope.$watch('PageConfig.page', function(newVals, oldVals){
                if(newVals != oldVals) {
                    $scope.data = gantt_data.slice(newVals * $scope.PageConfig.page_count + 1, (newVals + 1) * $scope.PageConfig.page_count);
                    // 重置scrollbar
                    angular.element('#panel_gantt')
                        .scrollTop(0)
                        .scrollLeft(0);
                }
            });
        }
];});
